<?php
/*
Plugin Name: blogger-import-fix
Description: <strong>WARNING!</strong> Enabling this plugin will automatically apply fixes on posts imported from Blogger. It will (1) replace images with their highest resolution version; (2) update slug to be same as Blogger; (3) replace Blogger read more anchor link to `&lt;!--more--&gt;` for WordPress. Note: Its success or results may vary. Please do a backup before activating!!
*/

/**
 * Fixes stuff that are Blogger specific but causes issues on WP.
 *
 * - Replaces the img tags with bigger image version from their parent `<a>`
 * tag.
 * - Replaces Blogger's read more tag
 */
function fix_blogger_stuff_for_wp( $html ) {
	$pattern = array(
		// td container is for when there is image caption, otherwise it's div or sometimes without div
		'/((?:<(?:div|td)[^>]+>))<a href="(https?:\/\/[^>]+(?:jpg|gif|png))"[^>]+><img alt="([^"]+)"[^>]+><\/a>((?:<\/(?:div|td)>))/U',
		'/((?:<(?:div|td)[^>]+>))<a href="(https?:\/\/[^>]+(?:jpg|gif|png))"[^>]+><img[^>]+><\/a>((?:<\/(?:div|td)>))/U',
		'/<a name=\'more\'><\/a>/'
		);
	$replacement = array(
		'$1<img src="$2" alt="$3" title="$3"/>$4',
		'$1<img src="$2" />$3',
		// `<a name='more'></a>` to `<!--more-->` for WordPress
		'<!--more-->'
	);

	$html = preg_replace( $pattern, $replacement, $html );
	return $html;
}

/**
 * Runs when Activating the plugin.
 *
 * Activating the plugin everytime runs the fixes. Common sense tells me it
 * should be ok to run it over already converted content.
 */
function blogger_fix_activate() {
	$posts = get_posts( array(
		'posts_per_page' => -1,
	) );
	if ( $posts ) {
		foreach ( $posts as $post ) :
			setup_postdata( $post );
			//$content = apply_filters( 'the_content', $post->post_content );
			// It will update the post content. So applying `the_content` filter
			// to it and then updating content may not be a good idea.
			$content = $post->post_content;
			// Applies changes for Blogger
			$content = fix_blogger_stuff_for_wp($content);
			// Update post content
			$new_post_data = array(
				'ID'           => $post->ID,
				'post_content' => $content,
			);
			// For fixing slug to be same as Blogger
			$permalink = get_post_meta( $post->ID, 'blogger_permalink', true );
			if ( ! empty( $permalink ) ) {
				$slug = explode("/",$permalink);
				$slug = explode(".",$slug[3]);
				$slug = $slug[0];
				$new_post_data['post_name'] = $slug;
			}
			wp_update_post( $new_post_data );
		endforeach;
		wp_reset_postdata();
	}
}
register_activation_hook( __FILE__, 'blogger_fix_activate' );
